package cn.opencodes.framework.autoconfigure;

import java.util.HashMap;
import java.util.Map;


import javax.sql.DataSource;


import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;


import cn.opencodes.framework.autoconfigure.properties.DynamicDataSourceProperties;
import cn.opencodes.framework.core.datasources.DynamicDataSource;
import cn.opencodes.framework.tools.utils.BeanUtils;

import cn.opencodes.framework.tools.utils.StringUtils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

/**
 * 配置多数据源
 * @author HJ
 */
@EnableTransactionManagement(order = 2)
public class DynamicDataSourceConfiguration {

	@Bean
	public DynamicDataSource dataSource(DynamicDataSourceProperties properties, DataSourceProperties parentProperties) {
		Map<String, DataSourceProperties> dataSourcePropertiesMap = properties.getDynamic();
        Map<String, DataSource> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
        final String[] tmp = new String[1];
        dataSourcePropertiesMap.forEach((k, v) -> {
        	DruidDataSource druidDataSource = DruidDataSourceBuilder.create().build();
        	BeanUtils.copyBeanNotNull2Bean(properties, druidDataSource);
        	BeanUtils.copyBeanNotNull2Bean(parentProperties, druidDataSource);
        	BeanUtils.copyBeanNotNull2Bean(v, druidDataSource);
            targetDataSources.put(k, druidDataSource);
            // 获取第一个数据源名称为默认数据源
            tmp[0] = StringUtils.isEmpty(tmp[0]) ? k : tmp[0];
        });
        
        DruidDataSource master = (DruidDataSource)targetDataSources.get(tmp[0]);
        return new DynamicDataSource(master, targetDataSources);
    }
    
}
